﻿
#include <iostream>
#include <iomanip>
#include "packet_buffer.h"

SDHWPacketBuffer::SDHWPacketBuffer() {

}

SDHWPacketBuffer::~SDHWPacketBuffer(){
    for (BuffData *bf : mBuffs){
        free(bf);
    }
    mBuffs.clear();
}

BuffData *SDHWPacketBuffer::obtain(BufferType type) {
    short len = 8;
    switch (type) {
        default: break;
    }

    for (auto it = mBuffs.begin(); it != mBuffs.end(); it++) {
        BuffData *bf = *it;
        if (bf->type == type && bf->slen == len) {
            bf->len = 0;
            mBuffs.erase(it);
            return bf;
        }
    }

    BuffData *bf = (BuffData *)calloc(1, sizeof(BuffData) + len);
    bf->type = type;
    bf->slen = len;
    bf->len  = 0;
    bzero(bf->buf, bf->slen);

    return bf;
}

void SDHWPacketBuffer::recycle(BuffData *buf) {
    bzero(buf->buf, buf->slen);
    mBuffs.push_back(buf);
}

int SDHWPacketBuffer::add(BuffData *buf, uchar *in_buf, int len) {

    return len;
}

bool SDHWPacketBuffer::complete(BuffData *buf) {

    return true;
}

bool SDHWPacketBuffer::compare(BuffData *src, BuffData *dst) {
    if (src->type != dst->type)
        return false;
    if (src->slen != dst->slen)
        return false;
    for (short i = 0; i < src->slen; i++) {
        if (src->buf[i] != dst->buf[i])
            return false;
    }
    return true;
}

bool SDHWPacketBuffer::check(BuffData *buf) {

    return true;
}

std::string SDHWPacketBuffer::str(BuffData *buf) {
    std::ostringstream oss;
    for (int i = 0; i < buf->slen; i++) {
        oss << std::hex << std::setfill('0') << std::setw(2) << (int)buf->buf[i] << " ";
    }
    return oss.str();
}

void SDHWPacketBuffer::check_code(BuffData *buf) {

}

IAck *SDHWPacketBuffer::ack(BuffData *bf) {

    return 0;
}
